<?php

class Dashboard extends Controller {
    public function __construct()
    {
        parent::__construct();
        $this->_data = array();
        $html = '<script type="text/javascript" src="'.js_url('libs/prototype/mila/wz_jsgraphics.js').'"></script>';
        $html .= '<script type="text/javascript" src="'.js_url('libs/prototype/mila/wz_jsgraphics.js').'"></script>';
        $html .= '<script type="text/javascript" src="'.js_url('libs/prototype/mila/tooltip.js').'"></script>';
        $html .= '<script type="text/javascript" src="'.js_url('libs/prototype/mila/mila.js').'"></script>';
        add_js_plugin('jqPlot/0.9.7/jquery.jqplot.js');
        add_js_plugin_css('jqPlot/0.9.7/jquery.jqplot.css');
        add_js_mod('nms-dashboard.js');
        add_content('head_end_before',$html);
        $this->load->module_model('nms','dashboard_model');
    }

    protected function _view($template, $data = array(), $result = false) {
        if ($data && is_array ( $data )) {
            return $this->load->view ( $template, $data, $result );
        }
        return $this->load->view ( $template, $this->_data, $result );
    }

    public function screenDetectionJs() {
        if ($this->input->post('action') == 'screen') {
            $this->session->screenWidth = (int)  trim($this->input->post('width'));
            $this->session->screenHeigh = (int)  trim($this->input->post('height'));
            if ($this->session->screenWidth < 1024)
                $this->session->screenWidth = 1024;
            if ($this->session->screenHeigh < 768)
                $this->session->screenHeigh = 768;
            $array = array('success'=>true,'fullscreen'=>true,'width'=>$this->session->screenWidth,'height'=>$this->session->screenHeigh);
            echo Zend_Json::encode($array);
        }
    }
    public function screenDetection($id = 0) {
        if (!$id) {
            $url = site_url('dashboard/view');
        } else {
            if (isset($this->session->$id))
                $url = $this->session->$id;
            else
                $url = site_url('dashboard/view');
        }
        $this->_data['redirectUrl'] = $url;
        $this->_view('dashboardScreenDetection');
    }
    public function jsListingLink() {
        $action = $this->input->post('action');
        $bid = $this->input->post('bid');
        if (!$action)
            $action = 'config';
        if (!$bid)
            $bid = 'all';
        if ($action = 'config') {
            $config = getDashboardConfig();
            if (isset($config['tipe']))
                $action = $config['tipe'];
            if (isset($config['list']) && $config['list'] && is_array($config['list']))
                $bid = $config['list'];
            
        }
        if ($action == 'one') {
            if (!is_array($bid))
                $bid = explode('|',$bid);
            if (!$bid || !is_array($bid)) {
                $action = 'all';
            }
        }
        if ($action == 'one') {
            $list = $this->dashboard_model->getNetworkStatus('ping',$bid);
        } else
            $list = $this->dashboard_model->getNetworkStatus();
        $row = $this->config->item('nms_server');
        $x = getDeviceWidth($row['networkX']) + 20;
        $y = $row['networkY'] + 20 ;
        $html = array();
        foreach($list as $row) {
            if ($row['networkX'] && $row['networkY'])
                $html[] = $x.','.$y.',' . (getDeviceWidth($row['networkX']) + 13 ) . ',' . ($row['networkY'] + 13);
        }
        if (!$html) return '';
        echo implode ('#',$html);
    }
    public function jsListing() {
        $action = $this->input->post('action');
        $bid = $this->input->post('bid');
        if (!$action)
            $action = 'config';
        if (!$bid)
            $bid = 'all';
        if ($action = 'config') {
            $config = getDashboardConfig();
            if (isset($config['tipe']))
                $action = $config['tipe'];
            if (isset($config['list']) && $config['list'] && is_array($config['list']))
                $bid = $config['list'];
            
        }
        if ($action == 'one') {
            if (!is_array($bid))
                $bid = explode('|',$bid);
            if (!$bid || !is_array($bid)) {
                $action = 'all';
            }
        }
        if ($action == 'one') {
            $list = $this->dashboard_model->getNetworkStatus('ping',$bid);
        } else
            $list = $this->dashboard_model->getNetworkStatus();
        $i = 1;
        $row = $this->config->item('nms_server');
        $html = $this->_getDevice($row);
        $x = 300 ;
        $y = 300 ;
        foreach($list as $row) {
            $temp = $this->_getDevice($row);
            $html .= $temp ;
        }
        echo $html;
    }    
    protected function _getDevice($row) {
            if (!isset($row['networkX']) || !isset($row['networkY']))
                return '';
            $ip = $iplan = $row['networkIpLanCE'];
            $ipwan = '';
            $ipwangw = '';
            $ipwanstatus = '';
            $ipwangwstatus = '';
            if (!empty($row['networkIpWanPE'])) {
                $ipwan = $row['networkIpWanPE'];
                $ipcalc = getIpcalc($ipwan);
                $ipwangw = $ipcalc['GATEWAY'];
            }
            $hostname = $row['networkHostname'];
            $mac = $row['networkMacAddress'];
            if ($row['networkResponse'])
                $response = 'Response '.$row['networkResponse'];
            else
                $response = '';
            $uptime = '';
            if ($row['networkX'])
                $x0 = getDeviceWidth($row['networkX']);
            else
                $x0 = rand(100,600);
            if ($row['networkY'])
                $y0 = $row['networkY'];
            else
                $y0 = rand(100,600);
            $x1 = $x0 + 8 ; // 108;
            $y1 = $y0 +  5 ; //105;
            $x2 = $x0 - 13 ; //87;
            $y2 = $y0 + 40 ;// 140;
            $x3 = '';
            $y3 = '';
            $urlImgsh = theme_image_url('service/ping/sh/' . $row['networkTypeName'] . '.gif' ); //img/sh/linux.gif
            if ($row['networkStatus'])
                $urlImgStatus = theme_image_url('service/ping/up/' . $row['networkTypeName'] . '.gif' ); //img/sh/linux.gif
            else
                $urlImgStatus = theme_image_url('service/ping/down/' . $row['networkTypeName'] . '.gif' ); //img/sh/linux.gif
            $temp =<<<EOLEOL
<div style="position:absolute;left:${x1}px;top:${y1}px;"><img src=$urlImgsh width=36 height=36></div>
<div style="position:absolute;left:${x0}px;top:${y0}px;">
    <a href="#" onmouseout="F(event,'$ip')" onmouseover="F(event,'$ip')" onclick="return false">
        <img src=$urlImgStatus width=36 height=36 border=0 title="${response}">
    </a>
</div>
<div style="position:absolute;white-space:nowrap;left:${x2}px;top:${y2}px;font:10px/12px Arial,Helvetica,sans-serif; ">$ip <br />${hostname}</div>
<div id="t$ip" class="tip">
    <table width=100% border=0 cellspacing=0 cellpadding=0>
        <tr>
            <td align=center><b>$ip</b></td>
        </tr>
        <tr>
            <td>IP LAN: $iplan</td>
        </tr>
        <tr>
            <td>IP WAN: $ipwan $ipwanstatus </td>
        </tr>
        <tr>
            <td>IP WAN GATEWAY: $ipwangw $ipwangwstatus</td>
        </tr>
        <tr>
            <td>Mac Address: $mac</td>
        </tr>
        <tr>
            <td>$response</td>
        </tr>
    </table>
</div>
EOLEOL;
            return $temp;        
    }

    
    function view()
    {
        $array = $this->uri->uri_to_assoc(3,array('action','bid'));
        if (!$array['action'])
            $array['action'] = 'config';
        if (!$array['bid'])
            $array['bid'] = 'all';
        if (!screenDetect()) {
            $_sid = md5(crypt(time()));
            $this->session->$_sid = site_url('dashboard/view/action/' . $array['action'] . '/bid/' . $array['bid']);
            redirect('dashboard/screenDetection/' . $_sid);
            die();
        }
        initWidthHeigh();
        $urlUpdate = site_url('dashboard/jsListing');
        $urlLink = site_url('dashboard/jsListingLink');
        $_action = $array['action'];
        $_bid = $array['bid'];
        $html =<<<EOLEOL
    <script type="text/javascript">

    window.onload = function(){
            
        new Ajax.PeriodicalUpdater($("nodes"), "$urlUpdate", { method: 'post',parameters: {action: '${_action}',bid: '${_bid}'}, frequency: intervalRequest, onSuccess: updatePage });
         
         }
     function updatePage() {
       setTimer(intervalRequest);
       updateLines();
       var D = new Date();
           document.getElementById('date').innerHTML=DateFormat(D);
               
     }
                     
    var myGlobalHandlers = {
        onCreate: function(){
        Element.show('load');
        
         
    }, onComplete: function() {
              
        if(Ajax.activeRequestCount == 0){
        Element.hide('load');
        
        }
        }
    };
    
    Ajax.Responders.register(myGlobalHandlers);
    
    function F(event,msg) { 
     var t ='t'+msg; 
     showTip(event, t); 
    } 
    
    
    function updateLines() {
          var url = '${urlLink}';
      var pars = ''
      var myAjax = new Ajax.Request( url, { method: 'post', parameters: {action: '${_action}',bid: '${_bid}'}, onComplete: showResult });
      }
    
       function showResult(originalRequest)
       {
               var res = originalRequest.responseText;
        
        // draw lines here
     var jg = new jsGraphics("lines");
     document.getElementById('lines').innerHTML = '' 
     jg.setColor("#006699");
     var pairs = res.split("#");
     for (var i=0; i<pairs.length; i++) {
        xy = pairs[i].split(',');
        jg.drawLine(parseFloat(xy[0]),parseFloat(xy[1]),parseFloat(xy[2]),parseFloat(xy[3]));
     }
     jg.paint();
    }

     function pop_window(url,w,h) {
        var popit = window.open(url,'console','width='+w+',height='+h+'');
             
    }
    </script>
EOLEOL;
        add_content('head_end_before',$html);
        add_js_plugin('jqPlot/0.9.7/jquery.jqplot.js');
        add_js_plugin('jqPlot/0.9.7/plugins/jqplot.pieRenderer.js');
        add_js_plugin('jqPlot/0.9.7/plugins/jqplot.barRenderer.js');
        add_js_plugin('jqPlot/0.9.7/plugins/jqplot.categoryAxisRenderer.js');
        
/* 
        //$url1 = js_url('libs/jquery/plugin/jqPlot/0.9.7/plugins/jqplot.pieRenderer.js');
        //$url2 = js_url('libs/jquery/plugin/jqPlot/0.9.7/plugins/jqplot.barRenderer.js');
        //$url3 = js_url('libs/jquery/plugin/jqPlot/0.9.7/plugins/jqplot.categoryAxisRenderer.js');
<script type="text/javascript" src="${url1}"></script>        
<script type="text/javascript" src="${url2}"></script>        
<script type="text/javascript" src="${url3}"></script>        
 * */
        $html =<<<EOLEOL
<script type="text/javascript">
<!--
    jQuery(document).ready(function($){
        $.jqplot.config.enablePlugins = false;
        //setTimeout('updateSideBarOne()',10);
        updateSideBarOne();
        //setInterval('updateSideBarOne()',intervalRequest * 500);
        updateSideBarTwo();
        //setInterval('updateSideBarTwo()',intervalRequest * 500);
        updateSideBarThree();
        updateSideBarFour();
        //updateSideBarOne();
        //$('#pie1').html('asfasfasfasfasfasfas faf');
        //test(data);
        //test2();
    });
    

(function($) {
test = function(data) {
        plot1 = $.jqplot('pie1', data , {
          gridPadding: {top:0, bottom:0, left:0, right:0},
          seriesDefaults:{renderer:$.jqplot.PieRenderer, trendline:{show:false}, rendererOptions: { padding: 8, showDataLabels: true}},
                      legend:{
                          show:true, 
                          placement: 'outside', 
                          rendererOptions: {
                              numberRows: 1
                          }, 
                          location:'s',
                          marginTop: '15px'
                      }       
        });
    
};
test2 = function() {
        var s1 = [2, 6, 7, 10];
        var s2 = [7, 5, 3, 2];
        var ticks = ['a', 'b', 'c', 'd'];
        
        plot2 = $.jqplot('chart2', [s1, s2], {
            seriesDefaults: {
                renderer:$.jqplot.BarRenderer,
                pointLabels: { show: true }
            },
            axes: {
                xaxis: {
                    renderer: $.jqplot.CategoryAxisRenderer,
                    ticks: ticks
                }
            }
        });
    


};
})(jQuery);
//-->
</script>

EOLEOL;
        add_content('head_end_before',$html);
        
        $this->_view('dashboardListing');
    }
    
    

    public function updateSideBarOne() {
        if ($this->input->post('action') == 'data') {
            $timeRequest = $this->input->post('timeRequest').'_one';
            $_t = $timeRequest . '_type';
            $_idToday = $timeRequest . '_idToday';
            $_idWeek = $timeRequest . '_idWeek';
            $_type = '';
            if (!isset($this->session->$_t))
                $this->session->$_t = 'updown';
            $_type = $this->session->$_t;
            $result = array(
                'type' => '',
                'data' => array(),
                'title' => '',
                'next' => ''
            );
            switch ($_type) {
                case 'updown' :
                    $data  = $this->dashboard_model->getNetworkUpDown('ping');
                    $result['title'] = 'Up/Down';
                    $result['type'] = 'pieone';
                    $result['next'] = 'today';
                    $result['data'] = array(
                        array('Up',0),array('Down',0)
                    );
                    foreach($data as $row) {
                        if ($row['networkStatus']) {
                            $result['data'][0] = array('Up',(int) $row['jumlah']);
                        } else {
                            $result['data'][1] = array('Down',(int) $row['jumlah']);
                        }
                    }
                    $this->session->$_t = 'today';
                    break;
                case 'today' :
                    $this->session->$_t = 'week';
                    $limit = 2;
                    $_lastId = '';
                    if (!isset($this->session->$_idToday))
                        $this->session->$_idToday = 0;
                    $_lastId = $this->session->$_idToday;
                    $data = $this->dashboard_model->getNetworkStatusToday('ping',$_lastId,$limit);
                    if ($data) {
                        $result['title'] = 'Statistik Hari Ini';
                        $result['type'] = 'bartwo';
                        $result['next'] = 'week';
                        $result['data'] = array();
                        $s1 = array();
                        $s2 = array();
                        $ticks = array() ;
                        $list = array();
                        //print_R($data);
                        foreach($data as $row) {
                            if (!isset($list[$row['networkId']])) {
                                $list[$row['networkId']] = array(
                                    'ip'=>'','up'=>'0','down'=>'0'
                                );
                            }
                            $list[$row['networkId']]['ip'] = $row['networkIpLanCE'];
                            if ($row['networkStatus']) {
                                $list[$row['networkId']]['up'] = (int) $row['jumlah'];
                            } else {
                                $list[$row['networkId']]['down'] = (int) $row['jumlah'];
                            }
                        }
                        //print_R($list);
                        foreach($list as $k=>$row) {
                            $s1[] = $row['up'];
                            $s2[] = $row['down'];
                            $ticks[] = $row['ip'];
                            $this->session->$_idToday = $k;
                        }
                        $result['data'] = array($s1,$s2);
                        $result['ticks'] = $ticks;
                        
                        //get data next, jika ada maka tetep today
                        $_lastId = $this->session->$_idToday;
                        $data = $this->dashboard_model->getNetworkStatusToday('ping',$_lastId,$limit);
                        if ($data) {
                            //maka next adalah today, dan session adalah today
                            $this->session->$_t = 'today';
                            $result['next'] = 'today';
                        } else
                            $this->session->$_idToday = 0;
                    }
                    break;
                case 'week' :
                    $this->session->$_t = 'updown';
                    $limit = 2;
                    $_lastId = '';
                    if (!isset($this->session->$_idWeek))
                        $this->session->$_idWeek = 0;
                    $_lastId = $this->session->$_idWeek;
                    $data = $this->dashboard_model->getNetworkStatusLastDay('ping',$_lastId,$limit);
                    //print_R($data);
                    if ($data) {
                        $result['title'] = "Statistik Last Day " ;
                        
                        $result['type'] = 'bartwo';
                        $result['next'] = 'week';
                        $result['data'] = array();
                        $s1 = array();
                        $s2 = array();
                        $ticks = array() ;
                        $list = array();
                        //print_R($data);
                        foreach($data as $row) {
                            $result['title'] = "Statistik Last Day " . $row['networkIpLanCE'];
                            if (!isset($list[$row['tgl']])) {
                                $list[$row['tgl']] = array(
                                    'up'=>'0','down'=>'0'
                                );
                            }
                            if ($row['networkStatus']) {
                                $list[$row['tgl']]['up'] = (int) $row['jumlah'];
                            } else {
                                $list[$row['tgl']]['down'] = (int) $row['jumlah'];
                            }
                            $this->session->$_idWeek = $row['networkId'];
                        }
                        //print_R($list);
                        foreach($list as $k=>$row) {
                            $s1[] = $row['up'];
                            $s2[] = $row['down'];
                            $ticks[] = $k;
                            
                        }
                        $result['data'] = array($s1,$s2);
                        $result['ticks'] = $ticks;
                        
                        //get data next, jika ada maka tetep today
                        $_lastId = $this->session->$_idWeek;
                        $data = $this->dashboard_model->getNetworkStatusLastDay('ping',$_lastId,$limit);
                        if ($data) {
                            //maka next adalah today, dan session adalah today
                            $this->session->$_t = 'week';
                            $result['next'] = 'week';
                        } else
                            $this->session->$_idWeek = 0;
                    }
                    
                    break;
            }
            echo Zend_Json::encode($result);
        }
    }
    public function updateSideBarTwo() {
        if ($this->input->post('action') == 'data') {
            $id = $this->input->post('id');
            $limit = $this->input->post('limit');
            $limit = (int) $limit ;
            if (!$limit)
                $limit = 10;
            $list = $this->dashboard_model->getNetworkStatusLimit('ping',$id,$limit);
            if ($id && !$list) {
                $list = $this->dashboard_model->getNetworkStatusLimit('ping',0,$limit);
            }
            $array = array('html'=>'','id'=>0);
            if (!$list) {
                echo Zend_Json::encode($array);
                die();
            }
            $html = '<ul class="updown">';
            $id = 0;
            foreach($list as $row) {
                $html .= '<li>' . $row['networkIpLanCE'] ;
                $html .= ' (' . date('d M, H:i',SQLTimeToMKTime($row['networkStatusModifiedTime'])) . ') ';
                if ($row['networkStatus'])
                    $html .= '<img src="' . theme_image_url('arrowUp.png'). '" alt="Status Active" title="Status Active" />';
                else
                    $html .= '<img src="' . theme_image_url('arrowDown.png'). '" alt="Status Down" title="Status Down" />';
                $html .= '</li>';
                $id = $row['networkId'];
            }
            $html .= '</ul>';
            $array['html'] = $html ;
            $array['id'] = $id;
            echo Zend_Json::encode($array);
        }
    }

    public function updateSideBarThree() {
        if ($this->input->post('action') == 'data') {
            $timeRequest = $this->input->post('timeRequest').'_three';
            $_id = $timeRequest .'_id';
            $_lastId = '';
            $limit = 5;
            if (!isset($this->session->$_id))
                $this->session->$_id = 0;
            $_lastId = $this->session->$_id;
            $lastDown = $this->dashboard_model->getNetworkStatusId($_lastId,$limit,'ping',0,true);
            if (!$lastDown) {
                $lastDown = $this->dashboard_model->getNetworkStatusId(0,$limit,'ping',0,true);
            }
            $html =<<<EOLEOL
            <table>
                <thead>
                    <th>Network Down</th>
                    <th>Last Check</th>
                    <th>Last UP</th>
                </thead>
                <tbody>
EOLEOL;
            if ($lastDown) foreach($lastDown as $row) {
                $this->session->$_id = $row['networkId'];
                $ip = $row['networkIpLanCE'];
                $lastCheck = date('d M',SQLTimeToMKTime($row['networkStatusModifiedTime']));
                $lastCheck .= '<br />' . date('H:i',SQLTimeToMKTime($row['networkStatusModifiedTime']));
                $_temp = $this->dashboard_model->getLastUp('ping',$row['networkId'],$row['networkStatusModifiedTime']);
                $lastUp = '';
                if ($_temp) {
                    $lastUp = date('d M',SQLTimeToMKTime($_temp['networkStatusLogCreateTime']));
                    $lastUp .= '<br />' . date('H:i',SQLTimeToMKTime($_temp['networkStatusLogCreateTime']));
                }
            $html .=<<<EOLEOL
                    <tr>
                        <td>${ip}</td>
                        <td class="date">${lastCheck}</td>
                        <td class="date">${lastUp}</td>
                    </tr>
EOLEOL;
            }
            $html .=<<<EOLEOL
                </tbody>
            </table>
EOLEOL;
            echo $html;
        }
    }

}
